<template>
	<view class="wx-wrap">
		<view class="wrapper">
			<view class="draw-wrapper">
				<canvas canvas-id="firstCanvas" id="firstCanvas" @touchstart.stop="onTouchStart"
					@touchmove.stop="onTouchMove"></canvas>
			</view>
			<view class="select-wrapper">
				<view class="select-first">
					<view :class="['select-item', item.name == cate1 ? 'active' : '']"
						v-for="(item, index) in selectFirst" :key="item.id"
						@click="onselectChange(item.name, 'cate1', index)">
						{{item.label}}
					</view>
				</view>
				<!-- 身体和表情 -->
				<template v-if="firstIndex == 0 || firstIndex == 1">
					<view class="select-second">
						<view :class="['select-item', item.cate2 == cate2 ? 'active' : '']"
							v-for="(item, index) in categories" :key="index"
							@click="onselectChange(item.cate2, 'cate2')">
							{{item.cate2}}
						</view>
					</view>
					<view class="img-wrapper">
						<view :class="['img', currentImagePath == item.path ? 'active' : '']"
							v-for="(item, index) in materials" :key="index" @click="onImgClick(item)">
							<u-image :src="item.path" width="70px" height="70px" mode="widthFix"></u-image>
							<!-- <view class="icon" v-if="currentImagePath == item.path">
								<u-icon size="20" name="close-circle" color="#1989fa"></u-icon>
							</view> -->
						</view>
					</view>
				</template>
				<!-- 文字 -->
				<!-- <template v-if="firstIndex == 2">
					<view class="text-wrapper">
						<u-input placeholder="请输入文字" border="surround" v-model="text" :color="colors"
							@change="onTextChange"></u-input>
						<zebra-color-picker v-model="colors"></zebra-color-picker>
					</view>
				</template> -->
				<!-- 表情生成 -->
				<template v-if="firstIndex == 2">
					<view class="generate">
						<u-button type="primary" @click="onGenerateClick">生成表情</u-button>
					</view>
				</template>
			</view>
		</view>
		<u-tabbar v-model="cur" @change="onTabbarChange" :placeholder="true">
			<u-tabbar-item text="表情包" icon="server-man" name="emjio"></u-tabbar-item>
			<!-- <u-tabbar-item text="制作" icon="server-man" name="create"></u-tabbar-item> -->
			<u-tabbar-item text="其他玩法" icon="photo" name="play"></u-tabbar-item>
		</u-tabbar>
		<u-loading-page :loading="isloading" bg-color="rgba(0, 0, 0, .3)" loadingText=" "></u-loading-page>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				cur: 'create',
				selectFirst: [{
						id: 0,
						name: '身体',
						label: '选身体'
					},
					{
						id: 1,
						name: '脸部',
						label: '选表情'
					},
					// {
					// 	id: 2,
					// 	name: '贴文字',
					// 	label: '贴文字'
					// },
					{
						id: 3,
						name: '发表情',
						label: '发表情'
					}
				],
				cate1: '身体',
				firstIndex: 0,
				cate2: '',
				categories: [],
				materials: [],
				url: '',
				canvasImages: [],
				startX: 0,
				startY: 0,
				startDistance: 0,
				startAngle: 0,
				canvasImages: [], // 已绘制的图片数组
				currentImagePath: null, // 当前选中的图片索引
				bodyPath: null,
				facePath: null,
				colors: '#000',
				text: ''
			};
		},
		async onLoad() {
			this.getFirstList()
		},
		methods: {
			filterLatestByCateSimple(items) {
				const latestByCate = {};
				for (const item of items) {
					// 如果当前cate还没有记录，或者当前项是最新的（基于数组顺序）  
					if (!latestByCate[item.cate] || items.indexOf(latestByCate[item.cate]) < items.indexOf(item)) {
						latestByCate[item.cate] = item;
					}
				}
				// 将结果转换回数组（如果需要）  
				return Object.values(latestByCate);
			},

			onImgClick(item) {
				let that = this
				this.currentImagePath = item.path
				uni.getImageInfo({
					src: item.path,
					success(res) {
						const img = {
							src: res.path,
							x: 75 - item.width / 2, // 初始位置
							y: 75 - item.height / 2,
							width: item.width, // 初始宽高
							height: item.height,
							scale: 1,
							rotate: 0,
							scaleX: 1, // 用于水平翻转
							path: item.path,
							cate: that.cate1
						};
						that.canvasImages.push(img);
						that.canvasImages = that.filterLatestByCateSimple(that.canvasImages)
						that.drawAllImages();
					}
				})
			},
			// 绘制所有图片
			drawAllImages() {
				const ctx = uni.createCanvasContext('firstCanvas');
				ctx.clearRect(0, 0, 150, 150); // 清除之前的内容
				this.canvasImages.forEach(img => {
					ctx.save();
					ctx.translate(img.x + img.width / 2, img.y + img.height / 2); // 移动到图片中心
					ctx.rotate(img.rotate); // 旋转
					ctx.scale(img.scale * img.scaleX, img.scale); // 缩放
					ctx.drawImage(img.src, -img.width / 2, -img.height / 2, img.width, img.height); // 绘制图片
					ctx.restore();
				});
				console.log(this.canvasImages, 'xxx');
				ctx.draw();
			},
			// 处理单指滑动
			onTouchStart(event) {
				console.log(event, 'evvv');
				if (event.touches.length === 1) {
					this.startX = event.touches[0].clientX;
					this.startY = event.touches[0].clientY;
				} else if (event.touches.length === 2) {
					// 计算初始距离和角度
					this.startDistance = this.getDistance(event.touches[0], event.touches[1]);
					this.startAngle = this.getAngle(event.touches[0], event.touches[1]);
				}
			},
			onTouchMove(event) {
				console.log(event, this.currentImageIndex, 'move');
				if (event.touches.length === 1) {
					const dx = event.touches[0].clientX - this.startX;
					const dy = event.touches[0].clientY - this.startY;
					const img = this.canvasImages.filter(ele => ele.path == this.currentImagePath)[0];
					img.x += dx;
					img.y += dy;
					this.startX = event.touches[0].clientX;
					this.startY = event.touches[0].clientY;
					this.drawAllImages();
				} else if (event.touches.length === 2) {
					const img = this.canvasImages.filter(ele => ele.path == this.currentImagePath)[0];
					const currentDistance = this.getDistance(event.touches[0], event.touches[1]);
					const currentAngle = this.getAngle(event.touches[0], event.touches[1]);

					const scaleChange = currentDistance / this.startDistance;
					const angleChange = currentAngle - this.startAngle;

					img.scale *= scaleChange;
					img.rotate += angleChange;

					this.startDistance = currentDistance;
					this.startAngle = currentAngle;

					this.drawAllImages();
				}
			},
			getDistance(touch1, touch2) {
				return Math.sqrt(Math.pow(touch2.clientX - touch1.clientX, 2) + Math.pow(touch2.clientY - touch1.clientY,
					2));
			},
			getAngle(touch1, touch2) {
				return Math.atan2(touch2.clientY - touch1.clientY, touch2.clientX - touch1.clientX);
			},
			async getFirstList(type, name) {
				console.log(type, name, 'xxxx');
				const params = {
					cate1: this.cate1
				}
				const res = await uni.request({
					url: 'https://wx.umilu.com/maker/material',
					data: params
				})
				this.categories = res[1].data.categories
				this.cate2 = type == 'cate2' ? name : res[1].data.categories[0].cate2
				await this.getSecondList()
			},
			async getSecondList() {
				const params = {
					cate1: this.cate1,
					cate2: this.cate2
				}
				const res = await uni.request({
					url: 'https://wx.umilu.com/maker/material',
					data: params
				})
				this.materials = res[1].data.materials
			},
			onselectChange(name, type, index) {
				if (type == 'cate1') {
					this.firstIndex = index
				}
				this[type] = name
				this.getFirstList(type, name)
			},
			// onTextChange(val) {
			// 	const ctx = uni.createCanvasContext('firstCanvas');
			// 	ctx.fillText(val, 50, 50); //文字内容、x坐标，y坐标
			// 	ctx.font = 'normal'; // 字体
			// 	ctx.setFontSize(20) //设置字体大小，默认10
			// 	ctx.setFillStyle('#000') //文字颜色：默认黑色
			// 	ctx.fillText("width:" + ctx.measureText(this.text).width, 50, 50) //显示文字宽度
			// 	ctx.draw() 
			// },
			onGenerateClick() {
				uni.canvasToTempFilePath({ // 把画布转化成临时文件
					x: 0,
					y: 0,
					width: 150, // 截取的画布的宽
					height: 150, // 截取的画布的高
					destWidth: 150, // 保存成的画布宽度
					destHeight: 150, // 保存成的画布高度
					fileType: 'jpg', // 保存成的文件类型
					quality: 1, // 图片质量
					canvasId: 'firstCanvas', // 画布ID
					success(res) {
						uni.downloadFile({
							url: res.tempFilePath, //分享的图片的链接
							success: (res2) => {
								wx.showShareImageMenu({
									path: res2.tempFilePath
								})
							}
						})
					},
					fail() {
						uni.showToast({
							title: '保存失败，稍后再试',
							duration: 2000,
							icon: 'none'
						})
						wx.hideLoading();
					}
				})
			}
		}
	}
</script>
<style lang="scss" scoped>
	.wx-wrap {
		overflow: hidden;
	}

	.wrapper {
		width: 100%;
		overflow: hidden;

		.draw-wrapper {
			width: 100%;
			height: 200px;
			// position: fixed;
			top: 0;
			left: 0;
			background: #1989fa;
			z-index: 999;
			display: flex;
			justify-content: center;
			align-items: center;

			canvas {
				width: 150px;
				height: 150px;
				background: #fff;
				border-radius: 10px;
				overflow: hidden;
			}
		}

		.select-wrapper {
			box-sizing: border-box;

			.select-first {
				display: flex;
				justify-content: space-around;
				padding: 10px 40px;

				// .select-item {
				// 	margin-right: 100rpx;
				// }

				.select-item.active {
					color: #1989fa;
					position: relative;
				}

				.select-item.active::after {
					content: ' ';
					display: block;
					width: 50%;
					height: 5rpx;
					background: #1989fa;
					border-radius: 10rpx;
					position: absolute;
					left: 50%;
					transform: translate(-50%, 10rpx);
				}
			}

			.select-second {
				width: 100%;
				display: flex;
				overflow-x: auto;

				.select-item {
					flex-shrink: 0;
					margin-left: 10px;
					padding: 4rpx 10rpx;
					font-size: 24rpx;
				}

				.select-item.active {
					color: #fff;
					background: #1989fa;
					border-radius: 10rpx;
				}
			}

			.img-wrapper {
				width: 95%;
				margin: 10rpx auto;
				display: flex;
				flex-wrap: wrap;
				height: 50vh;
				overflow-y: auto;

				.img {
					width: 25%;
					display: flex;
					justify-content: center;
					align-items: center;
					box-sizing: border-box;
					padding: 4px;
					margin-top: 10px;
					position: relative;
					border-radius: 8px;
					box-shadow: 0 0 10px #eee;

					.icon {
						position: absolute;
						top: -10px;
						right: -10px;
					}

					/deep/ .u-image {
						display: flex;
						justify-content: center;
						align-items: center;
					}
				}

				.img.active {
					box-shadow: 0 0 10px #1989fa;
				}
			}

			.text-wrapper {
				width: 90%;
				box-shadow: 0 0 10px #eee;
				border-radius: 20px;
				padding: 10px;
				margin: 20px auto;
				display: flex;
				flex-direction: column;
				align-items: center;
				box-sizing: border-box;

				/deep/ .u-input {
					width: 80%;
					margin-bottom: 20px;
				}
			}

			.generate {
				display: flex;
				align-items: center;
				justify-content: center;
				margin: 20px auto;
				width: 50%;
			}
		}
	}
</style>